<template>
    <view class="commonList ovfxh">
        <u-sticky :enable="isShowSearch">
            <view class="searchInputStyle">
                <u-button type="primary" v-if="$gx.HasPermission(40502)" @click="addBtn()" class="addBtn">
                    <u-icon labelPos="bottom" class="codeIcon" name="plus" color="#fff" size="24"></u-icon>
                </u-button>
                <u-search v-model="filterData._UsingWireropeCode" placeholder="钢丝绳编码" :clearabled="true" :show-action="false" shape="square" @search="searchData" @clear="searchData"></u-search>
                <u-icon labelPos="bottom" @click="codeSearch(2)" class="codeIcon" name="scan" color="#BFBFBF" size="48"></u-icon>
            </view>
        </u-sticky>
        <view class="cons-ul">
            <touchView ref="touchViews" v-for="(item, index) in list" :key="item.autoID" @clearTouch="clearTouch">
                <view class="cons-li posr">
                    <view class="title topTitle">
                        <text class="label-name">在用绳编码：{{ item.usingWirerope_Code || "-" }}</text>
                    </view>
                    <u-line class="marb-20" color="#E5E5E5"></u-line>
                    <u-row gutter="0" class="mart-20 marb-20">
                        <u-col span="12" class="uni-commit">
                            <text class="label-name">在用绳名称：</text>
                            <text>{{ item.usingWirerope_Name || "-" }}</text>
                        </u-col>
                    </u-row>

                    <u-row gutter="0" class="mart-20 marb-20">
                        <u-col span="12" class="uni-commit">
                            <text class="label-name">在用绳矿山：</text>
                            <text>{{ item.usingWirerope_DepartmentName || "-" }}</text>
                        </u-col>
                    </u-row>

                    <u-row gutter="0" class="mart-20 marb-20">
                        <u-col span="12" class="uni-commit">
                            <text class="label-name">附件编码：</text>
                            <text>{{ item.code || "-" }}</text>
                        </u-col>
                    </u-row>

                    <u-row gutter="0" class="marb-30">
                        <u-col span="12" class="uni-commit">
                            <text class="label-name">附件名称：</text>
                            <text>{{ item.attrFileName || "-" }}</text>
                        </u-col>
                    </u-row>
                    <u-row gutter="0" class="marb-30">
                        <u-col span="12" class="uni-commit">
                            <text class="label-name">备注：</text>
                            <text>{{ item.remark || "-" }}</text>
                        </u-col>
                    </u-row>
                    <u-row gutter="0" class="marb-30">
                        <u-col span="12" class="uni-commit">
                            <text class="label-name">创建人姓名：</text>
                            <text>{{ item.createUserName || "-" }}</text>
                        </u-col>
                    </u-row>
                    <u-row gutter="0" class="marb-30">
                        <u-col span="12" class="uni-commit">
                            <text class="label-name">创建时间：</text>
                            <text>{{ item.createDate | ymd }}</text>
                        </u-col>
                    </u-row>

                    <u-row gutter="0" class="btnBox mart-20 marb-10">
                        <template>
                            <u-col span="3" v-if="$gx.HasPermission(40503)">
                                <u-button class="marr-10" type="error" size="small" @click="delItem(item, index)">删除</u-button>
                            </u-col>
                            <u-col span="3" v-if="$gx.HasPermission(40504)">
                                <u-button type="primary" size="small" @click="downLoad(item)">下载</u-button>
                            </u-col>
                        </template>
                    </u-row>
                </view>
            </touchView>
        </view>

        <searchPopup ref="searchPopup" @AdvanceSearch="searchData" @ClearSearch="clearSearch">
            <u--form :model="filterData" ref="searchForm" label-position="top" :labelWidth="120">
                <u-form-item label="附件名称">
                    <u--input v-model="filterData._AttrFileName" placeholder="请输入附件名称" prefixIconStyle="font-size: 22px;color: #909399"></u--input>
                </u-form-item>
                <u-form-item label="钢丝绳名称">
                    <u--input v-model="filterData._UsingWireropeName" placeholder="请输入钢丝绳名称" prefixIconStyle="font-size: 22px;color: #909399"></u--input>
                </u-form-item>
                <u-form-item label="矿山">
                    <ld-select class="ldSel w-100" :multiple="true" label-key="name" value-key="autoID" table="Department" action="GetSearchWithIsDelete" :filter="{ _Type: $enums.Department_Type.矿山 }" label="name" value="autoID" placeholder="请选择矿山" clearable v-model="filterData._UsingWireropeDepartmentIDs" @change="statusChange"></ld-select>
                </u-form-item>
                <u-form-item label="实施日期" @click="calendarShow = true">
                    <u--input v-model="BillDate" type="text" disabledColor="#ffffff" placeholder="点击选择时间" disabled />
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>
                <u-calendar :show="calendarShow" mode="range" @close="calendarShow = false" @confirm="changeCalendar"></u-calendar>
            </u--form>
        </searchPopup>

        <view class="hei-30"></view>
    </view>
</template>

<script>
import ldSelect from "@/components/ld-select/ld-select.vue";
export default {
    components: {
        ldSelect,
    },
    data() {
        return {
            //查询分页所需要的数据
            pageIndex: 1,
            pageSize: 10,
            totalCount: 0,
            orderBy: "[x].[UsingWireropeAttrID] DESC",
            imageExts: ["png", "jpg", "jpeg", "gif", "bmp", "tiff", "pjp", "jfif", "svg", "xbm", "dib", "jxl", "svgz", "webp", "ico", "tif", "pjpeg", "avif"], //图片类型的扩展名
            fileExts: ["doc", "xls", "ppt", "pdf", "docx", "xlsx", "pptx"],

            //搜索条件对象
            filterData: {
                _UsingWireropeCode: "",
                _UsingWireropeDepartmentIDs: [],
            },
            list: [], //列表数据

            hasMore: true, //是否可以加载更多
            isShowSearch: true, //是否显示顶部搜索框，这里不是为了控制显示不显示，而是要处理在离开本页时把这个隐藏，否则会报错

            calendarShow: false,
            BillDate: "",
        };
    },
    //生命周期-显示
    onReady() {
        this.isShowSearch = true;
        this.GetPage();
    },

    //生命周期-隐藏
    onHide() {
        this.isShowSearch = false;
    },

    onShow() {
        uni.$off("refreshData");
        uni.$on("refreshData", (res) => {
            this.RefreshData();
        });
    },

    //生命周期-下拉刷新
    onPullDownRefresh() {
        this.RefreshData();
    },

    //生命周期-上拉加载更多
    onReachBottom() {
        if (this.hasMore) {
            this.pageIndex++;
            this.GetPage();
        }
    },

    onNavigationBarButtonTap(e) {
        if (e.text == "筛选") {
            this.show = false;
            this.$nextTick(() => {
                this.$refs.searchPopup.init();
            });
        }
    },

    methods: {
        addBtn() {
            this.showDetailDialog({}, "新增");
        },
        statusChange(val) {
            this.$set(this.filterData, "_UsingWireropeDepartmentIDs", val);
        },

        //扫码
        codeSearch(type) {
            uni.scanCode({
                onlyFromCamera: true,
                scanType: ["qrCode"],
                success: (res) => {
                    if (!this.$gx.IsEmpty(res.result)) {
                        let code = res.result;
                        this.filterData._UsingWireropeCode = code;
                        this.searchData();
                    } else {
                        this.$app.Tips({
                            title: "扫码信息格式不正确！",
                        });
                    }
                },
                fail: () => {
                    // this.$app.Tips({ title: "扫码失败，请联系管理员！" });
                },
                complete: () => {},
            });
        },
        // 回退所有的touchView
        clearTouch() {
            this.$refs.touchViews.forEach((element) => {
                element.hide();
            });
        },
        //分页
        GetPage(clearFlag) {
            const own = this;
            this.$app.ShowLoading();
            if (clearFlag) this.list = [];
            this.$app.CallApi(this.$app.api.UsingWireropeAttr.GetPage(this.pageIndex, this.pageSize, this.orderBy), {
                data: this.filterData,
                success: (res) => {
                    this.totalCount = res.totalCount;
                    this.list = this.list.concat(res.items);
                    this.$app.HideLoading();
                    if (this.totalCount <= this.list.length) {
                        this.hasMore = false;
                    }
                },
            });
        },

        searchData() {
            this.RefreshData();
        },

        //搜索
        RefreshData() {
            this.pageIndex = 1;
            this.list = [];
            this.hasMore = true;
            this.GetPage();
        },
        //打开详情
        showDetailDialog(row, operateType) {
            let url = "/pages/usingWireropeAttr/detail";
            uni.navigateTo({
                url: url,
                success: function (res) {
                    res.eventChannel.emit("editData", {
                        data: row,
                        operateType: operateType,
                    });
                },
            });
        },
        //清空搜索项
        clearSearch() {
            this.filterData._AttrFileName = "";
            this.filterData._UsingWireropeName = "";
            this.filterData._UsingWireropeCode = "";
            this.filterData._UsingWireropeDepartmentIDs = [];

            this.BillDate = "";
            this.filterData._CreateDate_Begin = null;
            this.filterData._EndDate_End = null;

            this.searchData();
        },
        //选择日期
        changeCalendar(data) {
            this.filterData._CreateDate_Begin = data[0];
            this.filterData._EndDate_End = data[data.length - 1];
            this.BillDate = data[0] + "-" + data[data.length - 1];
            this.calendarShow = false;
        },
        //删除
        delItem(item, index) {
            let that = this;
            this.$app.Confirm({
                msg: "您确定要删除当前附件监测记录吗？",
                success: (res) => {
                    if (res.confirm) {
                        that.$app.CallApi(that.$app.api.UsingWireropeAttr.Delete(item.usingWireropeAttrID), {
                            success: (_) => {
                                that.$u.toast("删除成功!");
                                that.list.splice(index, 1);
                            },
                        });
                    }
                },
            });
        },
        //下载
        downLoad(item) {
            let url = item.attrFileUrl;
            // #ifdef APP-PLUS
            uni.showLoading({ title: "开始下载并保存，请稍后！" });
            uni.downloadFile({
                url: url,
                success: (downRes) => {
                    if (downRes.statusCode === 200) {
                        let fileName = downRes.tempFilePath.substring(downRes.tempFilePath.lastIndexOf(".") + 1);
                        let findIndex1 = this.imageExts.findIndex((x) => {
                            return x === fileName;
                        });
                        if (findIndex1 != -1) {
                            //图片
                            uni.saveImageToPhotosAlbum({
                                filePath: downRes.tempFilePath,
                                success: () => {
                                    this.$app.Tips({ title: "保存成功！", icon: "none" });
                                    return;
                                },
                                fail: () => {
                                    this.$app.Tips({ title: "保存失败！" });
                                    return;
                                },
                            });
                        } else {
                            //文件
                            uni.saveFile({
                                tempFilePath: downRes.tempFilePath,
                                success: (saveRes) => {
                                    let fileInfo2 = this.$gx.GetUrlFileName(saveRes.savedFilePath);

                                    let findIndex2 = this.fileExts.findIndex((x) => {
                                        return x === fileInfo2.extName.toLowerCase();
                                    });

                                    if (findIndex2 != -1) {
                                        this.$app.Tips({
                                            title: "正在打开文件...",
                                            icon: "none",
                                        });
                                        uni.openDocument({
                                            filePath: saveRes.savedFilePath,
                                            success: (res) => {},
                                            fail() {
                                                this.$app.Tips({ title: "打开失败！" });
                                            },
                                        });
                                    } else {
                                        this.$app.Tips({
                                            title: "保存成功！",
                                            icon: "none",
                                        });
                                    }
                                },
                                fail() {
                                    this.$app.Tips({ title: "保存失败！" });
                                },
                            });
                        }
                    }
                },
                fail() {
                    this.$app.Tips({ title: "保存失败！" });
                },
                complete() {
                    uni.hideLoading();
                },
            });
            // #endif
        },
    },
};
</script>

<style scoped>
.commonList .cons-li {
    background-color: white;
}

.noPadding {
    padding: 0px !important;
}

.btnBox {
    justify-content: center !important;
    margin-left: -20rpx;
    margin-right: -20rpx;
}

.btnBox ::v-deep .u-col {
    min-width: 130rpx;
    margin-left: 20rpx;
    margin-right: 20rpx;
}

.searchInputStyle {
    display: flex;
    align-items: center;
}

.topTitle {
    display: flex;
}

.topTitle .label-name {
    flex: 2;
}
</style>
